package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.exception.DisplayableException;
import cn.wolfcode.p2p.base.service.IVerifyCodeService;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.DateUtil;
import cn.wolfcode.p2p.base.vo.VerifyCodeVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpSession;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.UUID;

/**
 * Created by wolfcode on 2018/7/22.
 */
@Service@Transactional
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    public void sendVerifyCode(String phoneNumber, HttpSession session) {
        //判断一下上次发送的时间和现在的时间是否超过90秒
        VerifyCodeVo vo = (VerifyCodeVo) session.getAttribute("VERIFYCODE_IN_SESSION");
        //上一次发送的时候-当前时间 > 90
        if(vo==null || DateUtil.getTimeBetween(vo.getSendTime(),new Date())>90){
            //1.生成4位手机认证码.
            String randomCode = UUID.randomUUID().toString().substring(0,4);
            //2.拼接短信内容
            StringBuilder msg = new StringBuilder(50);
            msg.append("这是您的手机认证码:").append(randomCode).append(",请尽快使用,验证码的有效时间为").append(Constants.VERIFYCODE_VAILD_TIME).append("分钟");
            //3.执行真正的短信发送(TODO)
            //System.out.println(msg);
            try {
                //sendRealMsg(phoneNumber,msg.toString());
                //4.需要把验证码和发送的手机,发送的时间到sesison中\
                System.out.println(msg);
                vo = new VerifyCodeVo();
                vo.setRandomCode(randomCode);
                vo.setPhoneNumber(phoneNumber);
                vo.setSendTime(new Date());
                session.setAttribute("VERIFYCODE_IN_SESSION",vo);
            } catch (Exception e) {
                throw new DisplayableException(e.getMessage());
            }
        }else{
            throw new DisplayableException("您操作太频繁了,请稍后再试!");
        }
    }
    private void sendRealMsg(String phoneNumber,String msg) throws Exception {
        //1.定义需要访问的地址
        URL url = new URL("http://utf8.api.smschinese.cn");
        //2.通过url获取远程的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3.设置请求的配置信息
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        //4.给该地址拼接参数
        StringBuilder param = new StringBuilder(50);
        param.append("Uid=").append("lanxw03")
                .append("&Key=").append("d41d8cd98f00b203e680")
                .append("&smsMob=").append(phoneNumber)
                .append("&smsText=").append(msg);
        //把参数输出到对方服务器中
        conn.getOutputStream().write(param.toString().getBytes(Charset.forName("utf-8")));
        //发起连接
        conn.connect();
        //获取对方服务器给响应数据
        String respCodeStr = StreamUtils.copyToString(conn.getInputStream(),Charset.forName("utf-8"));
        int respCode = Integer.parseInt(respCodeStr);
        if(respCode<0){
            System.out.println(respCode);
            throw new DisplayableException("短信接口异常,请联系管理员");
        }
    }
}
